﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using StackExchange.Redis;

namespace Jack.RedisLib
{
    public partial class RedisClient
    {
        public async Task<(bool ExecuteResult, Exception Exception)> TransactionExecute(Func<ITransaction, Task> task, int db = -1, object asyncState = null, CancellationToken cancellationToken = default)
        {
            IDatabase database = await GetConnectedDatabase(db, cancellationToken);
            if (database == null) return (false, default);

            ITransaction tran = database.CreateTransaction();
            bool execute = false;
            Exception exception = null;
            try
            {
                await task(tran);
                execute = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                exception = ex;
                execute = false;
            }
            finally
            {
                execute = await tran.ExecuteAsync() && execute;
            }

            return (execute, exception);
        }
    }
}
